#!/usr/bin/env bash

# 启用严格模式，遇错终止
set -euo pipefail

SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
PROJECT_ROOT=$(dirname "$(dirname "$SCRIPT_DIR")")
echo "脚本所在目录：$SCRIPT_DIR"
echo "上上级目录（PROJECT_ROOT）：$PROJECT_ROOT"
IMAGE_REPO="registry.cn-hangzhou.aliyuncs.com/my_public_images"

# 默认服务名和 RPC 目录标志
SERVICE_NAME=${1:-user}        # 第一个参数：服务名
USE_RPC=${2:-"--use-rpc"}      # 第二个参数：是否使用 rpc 目录
YAML_FILE="${PROJECT_ROOT}/deploy/etcs/${SERVICE_NAME}.yaml"  # 配置文件路径
DOCKERFILE_TEMP="${PROJECT_ROOT}/deploy/dockers/${SERVICE_NAME}.dockerfile"  # Dockerfile

### 清理旧文件
echo "清理旧文件..."
rm -f "${DOCKERFILE_TEMP}"
rm -f "${PROJECT_ROOT}/deploy/scripts/entrypoint.sh"

### 一、获取与容器同网段的宿主机IP（核心逻辑） ###
# 定义需要匹配的网段（根据实际情况修改，支持多个网段）
declare -a TARGET_NETWORKS=("10." "172." "192.168.")  # 示例：匹配10.x、172.x、192.168.x网段

# 获取所有非回环IP地址
ALL_IPS=$(ip -o addr show | awk '{gsub(/\/.*/,""); if ($4 != "lo") print $4}')

# 筛选符合目标网段的IP（优先匹配第一个符合条件的IP）
HOST_IP=""
for ip in $ALL_IPS; do
    for network in "${TARGET_NETWORKS[@]}"; do
        if [[ "$ip" == "$network"* ]]; then
            HOST_IP="$ip"
            break 2  # 找到第一个匹配IP后退出循环
        fi
    done
done

# 若未找到，报错并退出
if [ -z "$HOST_IP" ]; then
    echo "错误：未找到与容器同网段的IP（目标网段：${TARGET_NETWORKS[*]}）"
    exit 1
fi
echo "找到目标IP：$HOST_IP"

### 二、替换YAML配置文件中的127.0.0.1为宿主机IP ###
echo "正在修改配置文件：$YAML_FILE"

# 转义IP地址中的点号，用于正则表达式
ESCAPED_IP=$(echo "$HOST_IP" | sed 's/\./\\./g')

# 根据配置文件类型执行不同的替换策略
if grep -q "consul://127.0.0.1" "$YAML_FILE"; then
    # 针对api.yaml格式的替换
    sed -i'' "s/consul:\/\/127\.0\.0\.1/consul:\/\/${ESCAPED_IP}/g" "$YAML_FILE"
    echo "已替换consul地址格式"
else
    # 针对user.rpc.yaml格式的替换
    sed -i'' "s/Host: 127\.0\.0\.1/Host: ${ESCAPED_IP}/g" "$YAML_FILE"
    sed -i'' "s/Path: 127\.0\.0\.1/Path: ${ESCAPED_IP}/g" "$YAML_FILE"
    echo "已替换标准Host/Path格式"
fi

# 验证修改结果
echo "验证配置文件修改..."
if grep -q "$HOST_IP" "$YAML_FILE"; then
    echo "配置替换成功"
    echo "替换后的配置片段:"
    grep -A3 -B3 "$HOST_IP" "$YAML_FILE"
else
    echo "错误：配置替换失败"
    exit 1
fi

### 三、原有编译和构建流程 ###
echo "Building service: ${SERVICE_NAME}"
echo "RPC 目录模式: ${USE_RPC}"

# 清理旧二进制文件
BIN_DIR="${PROJECT_ROOT}/bin"
mkdir -p "${BIN_DIR}"
cd "${BIN_DIR}" || exit
echo "Cleaning ${SERVICE_NAME} binaries in $(pwd)..."
rm -f "${SERVICE_NAME}"

# 根据标志选择编译目录(自主选择是否使用rpc目录)
if [[ "$USE_RPC" == "--use-rpc" ]]; then
    COMPILE_DIR="${PROJECT_ROOT}/apps/${SERVICE_NAME}/rpc"
else
    COMPILE_DIR="${PROJECT_ROOT}/apps/${SERVICE_NAME}"
fi

cd "${COMPILE_DIR}" || {
    echo "错误: 目录不存在: ${COMPILE_DIR}"
    exit 1
}

echo "Compiling ${SERVICE_NAME} service from $(pwd)..."
CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w -extldflags '-static'" -o "${BIN_DIR}/${SERVICE_NAME}" .

# 压缩二进制文件
cd "${BIN_DIR}" || exit
echo "Compressing ${SERVICE_NAME} binary with UPX..."
if command -v upx &> /dev/null; then
    upx -9 "${SERVICE_NAME}"
else
    echo "UPX not found, skipping compression"
fi

# 动态生成 Dockerfile
echo "生成 Dockerfile 到 ${DOCKERFILE_TEMP}"
mkdir -p "$(dirname "${DOCKERFILE_TEMP}")"
cat > "${DOCKERFILE_TEMP}" <<EOF
FROM alpine:3.18
WORKDIR /app
COPY bin/${SERVICE_NAME} /app/
COPY deploy/etcs/${SERVICE_NAME}.yaml /app/etc/
RUN chmod +x /app/${SERVICE_NAME}
CMD ["/app/${SERVICE_NAME}", "-f", "/app/etc/${SERVICE_NAME}.yaml"]
EOF

# 构建并推送 Docker 镜像
cd "${PROJECT_ROOT}" || exit
echo "Building Docker image for ${SERVICE_NAME}..."
docker build \
  -f "${DOCKERFILE_TEMP}" \
  -t "${SERVICE_NAME}:latest" .

echo "Tagging and pushing ${SERVICE_NAME} image to registry..."
docker tag "${SERVICE_NAME}:latest" "${IMAGE_REPO}/${SERVICE_NAME}:latest"
docker push "${IMAGE_REPO}/${SERVICE_NAME}:latest"

echo "${SERVICE_NAME} service built and deployed successfully!"